<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Listen Controller
 *
 * Accepts requests from the local application and return the necessary response data
 *
 * @package     VisualQ Local System
 * @author      CSU OJT Students '10 - '11 (Michael Roland B. Martin)
 * @copyright   Copyright (c) 2010 - 2011, Bitstop Network Services, Inc.
 * @version     1.0 January 27, 2011
 */

class Listen extends Controller {

    function index()
    {
        $this->load->library('xmlrpc');
        $this->load->library('xmlrpcs');

        $config['functions']['initializeSettings']          = array('function' => 'Listen.initialize_settings');
        $config['functions']['initializeServices']          = array('function' => 'Listen.initialize_services');
        $config['functions']['initializeAccounts']          = array('function' => 'Listen.initialize_accounts');
        $config['functions']['initializeAccountsServices']  = array('function' => 'Listen.initialize_accounts_services');
        $config['functions']['checkUpdates']                = array('function' => 'Listen.check_updates');
        $config['functions']['checkAds']                    = array('function' => 'Listen.check_ads');
        $config['functions']['getAd']                       = array('function' => 'Listen.get_ad');
        $config['functions']['getUpdates']                  = array('function' => 'Listen.get_updates');
        $config['functions']['getClientUpdates']            = array('function' => 'Listen.get_client_updates');
        $config['functions']['getBranchUpdates']            = array('function' => 'Listen.get_branch_updates');
        $config['functions']['receiveLogs']                 = array('function' => 'Listen.receive_logs');
        $config['functions']['receiveStatistics']           = array('function' => 'Listen.receive_statistics');
        $config['functions']['deactivate']                  = array('function' => 'Listen.deactivate');

        $this->xmlrpcs->initialize($config);
        $this->xmlrpcs->serve();
    }

    /**
     * Build select and join statements for the initialize and update methods
     *
     * Used by:
     *      listen/initialize_services/
     *      listen/initialize_accounts/
     *      listen/initialize_accounts_services/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	array
     *      table   :   table name
     * @return  string
     *      id      :   id field to be used
     */
    function build_select($table)
    {
        if(strcmp($table, 'services') == 0)
        {
            $id = 'client_services.id';
            $this->db->select('clients_services.id as id, title, prefix, closing_codes, description');
            $this->db->join('services', 'clients_services.service_id = services.id');
        }
        if(strcmp($table, 'agents') == 0)
        {
            $id = 'accounts.id';
            $this->db->select('accounts.*, agents.id as agent_id');
            $this->db->join('accounts', 'accounts.id = agents.account_id');
        }
        if(strcmp($table, 'agents_services') == 0)
        {
            $id = 'agents_services.id';
            $this->db->select('agents_services.id as id, account_id, client_service_id as service_id');
            $this->db->join('agents', 'agents_services.agent_id = agents.id');
        }

        return $id;
    }

    function check_ads($request)
    {
        $this->load->helper('directory');

        $filenames = check_directory("ads/", "flv");

        $response = array(
            array(
                'response'  => 0
            ),
            'struct'
        );

        foreach ($filenames as $name)
        {
            $ad_path = 'ads/' . $name;
            if(@file_exists($ad_path))
            {
                $ad[] = $name;
            }

            $response = array(
                array(
                    'ad'        => array($ad, 'array'),
                    'response'  => 1
                ),
                'struct'
            );
        }
        return $this->xmlrpc->send_response($response);
    }

    function get_ad($request)
    {
        //  0   :   filename
        $parameters = $request->output_parameters();

        $this->load->helper('directory');

        $filenames = check_directory("ads/", "flv");

        $response = array(
            array(
                'response'  => 0
            ),
            'struct'
        );
        foreach ($filenames as $name)
        {
            if(strcmp($name, $parameters[0]) == 0)
            {
                $ad_path = 'ads/' . $name;
                
                if(@file_exists($ad_path))
                {
                    $ad = base64_encode(file_get_contents($ad_path));
                }

                $response = array(
                    array(
                        'ad'        => $ad,
                        'response'  => 1
                    ),
                    'struct'
                );
            }
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Verify the validation key and product key, returns the client and brach data and settings
     *
     * Used by: (Local App)
     *      sync/initialize_settings/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function initialize_settings($request)
    {
        //  0   :   validation key
        //  1   :   product key
        $parameters = $request->output_parameters();

        // Check if the validation key and product key combination matches a record
        $this->db->select('branches.id as id');
        $this->db->join('clients', 'branches.client_id = clients.id');
        $this->db->where('validation_key', $parameters[0]);
        $this->db->where('product_key', $parameters[1]);
        $query = $this->db->get('branches');

        // Check if there is a match
        if($query->num_rows() > 0)
        {
            // Get the branch id
            $branch = $query->row_array();

            // Check if the branch is already activated
            $this->db->select('clients.name as `company_name`, logo, branches.name as `branch_name`, street_address, city, state, country_id, contact_number, validation_key, product_key, client_id, branches.id as branch_id');
            $this->db->join('clients', 'branches.client_id = clients.id');
            $this->db->where('branches.id', $branch['id']);
            $this->db->where('activated', 0);
            $query = $this->db->get('branches');

            // Check if there is a record found
            if($query->num_rows() > 0)
            {
                // Get the necessary client and branch data and settings
                $branch = $query->row_array();

                // Set the branch as activated
                $this->db->where('id', $branch['branch_id']);
                $this->db->update('branches', array('activated' => 1));

                // Check if logo exists
                if($branch['logo'])
                {
                    $logo = 'usr/' . $branch['client_id'] . '/logo.' . $branch['logo'];
                    if(@file_exists($logo))
                    {
                        $branch['logo_str'] = base64_encode(file_get_contents($logo));
                    }
                }

                // Prepare the client and branch data and settings
                foreach($branch as $key => $value)
                {
                    $settings[] = array(
                        array(
                            'name'  => $key,
                            'value' => $value
                        ),
                        'struct'
                    );
                }

                $response = array(
                    array(
                        'settings'  => array($settings, 'array'),
                        'response'  => 'done'
                    ),
                    'struct'
                );
            }
            else
            {
                // The validation key and product key combination is already in use
                $response = array(
                    array(
                        'response'  => 'in_use'
                    ),
                    'struct'
                );
            }
        }
        else
        {
            // The validation key and product key combination doesn't match any record
            $response = array(
                array(
                    'response'  => 'invalid'
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the client specific services
     *
     * Used by: (Local App)
     *      sync/initialize_services/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function initialize_services($request)
    {
        //  0   :   client id
        $parameters = $request->output_parameters();

        $this->build_select('services');

        // Get the client services
        $this->db->where('client_id', $parameters[0]);
        $query = $this->db->get('clients_services');

        // Check if there are set services
        if($query->num_rows() > 0)
        {
            // Prepare the client services
            foreach($query->result_array() as $row)
            {
                $services[] = array(
                    $row,
                    'struct'
                );
            }

            $response = array(
                array(
                    'services'  => array($services, 'array'),
                    'response'  => 1
                ),
                'struct'
            );
        }
        else
        {
            // No client services found
            $response = array(
                array(
                    'response'  => 0
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the branch specific accounts (branch manager and agent accounts)
     *
     * Used by: (Local App)
     *      sync/initialize_accounts/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function initialize_accounts($request)
    {
        //  0   :   branch id
        $parameters = $request->output_parameters();

        // Check for the manager account
        $this->db->select('accounts.*');
        $this->db->join('branches', 'branches.account_id = accounts.id');
        $this->db->where('branches.id', $parameters[0]);
        $query = $this->db->get('accounts');

        // Check if there is an account
        if($query->num_rows() > 0)
        {
            // Prepare the branch manager account
            foreach($query->result_array() as $row)
            {
                $accounts[] = array(
                    $row,
                    'struct'
                );
            }

            $this->build_select('agents');

            // Check for the agent accounts
            $this->db->where('branch_id', $parameters[0]);
            $query = $this->db->get('agents');

            // Check if there are agent accounts for the branch
            if($query->num_rows() > 0)
            {
                // Prepare the agent accounts
                foreach($query->result_array() as $row)
                {
                    $accounts[] = array(
                        $row,
                        'struct'
                    );
                }
            }

            $response = array(
                array(
                    'accounts'  => array($accounts, 'array'),
                    'response'  => 1
                ),
                'struct'
            );
        }
        else
        {
            // No branch manager account found
            $response = array(
                array(
                    'response'  => 0
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the ids and change status of client data
     *
     * Used by: (Local App)
     *      sync/check_updates/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function check_updates($request)
    {
        //  0   :   client id
        //  1   :   branch id
        $parameters = $request->output_parameters();

        // Check if the client id matches a record
        $this->db->where('id', $parameters[0]);
        $query = $this->db->get('clients');

        // Check if there is a match
        if($query->num_rows() > 0)
        {
            $row    = $query->row_array();
            $client = 1;

            // Check if the branch id matches a record
            $this->db->where('id', $parameters[0]);
            $query = $this->db->get('branches');

            // Check if there is a match
            if($query->num_rows() > 0)
            {
                $row    = $query->row_array();
                $branch = $row['changed'];

                // Check for client services
                $this->db->select('id, changed');
                $this->db->where('client_id', $parameters[0]);
                $query = $this->db->get('clients_services');

                // Check if there client services
                if($query->num_rows() > 0)
                {
                    // Prepare the client services
                    foreach($query->result_array() as $row)
                    {
                        $services[] = array(
                            $row,
                            'struct'
                        );
                    }
                }
                else
                {
                    $services = NULL;
                }

                // Check for agent accounts for the branch
                $this->db->select('account_id as id, changed');
                $this->db->where('branch_id', $parameters[1]);
                $query = $this->db->get('agents');

                // Check if there are agent accounts
                if($query->num_rows() > 0)
                {
                    // Prepare the agent accounts
                    foreach($query->result_array() as $row)
                    {
                        $accounts[] = array(
                            $row,
                            'struct'
                        );

                        // Get the agent id of the agents
                        $this->db->where('account_id', $row['id']);
                        $query = $this->db->get('agents');
                        $agent = $query->row_array();
                        $ids[] = $agent['id'];
                    }
                }
                else
                {
                    $accounts = NULL;
                }

                // Check for the agent services
                $this->db->select('id');
                $this->db->where_in('agent_id', $ids);
                $query = $this->db->get('agents_services');

                // Check if there are agent services
                if($query->num_rows() > 0)
                {
                    // Prepare the agent services
                    foreach($query->result_array() as $row)
                    {
                        $accounts_services[] = array(
                            $row,
                            'struct'
                        );
                    }
                }
                else
                {
                    $accounts_services = NULL;
                }

                $response = array(
                    array(
                        'client'            => $client,
                        'branch'            => $branch,
                        'services'          => array($services, 'array'),
                        'accounts'          => array($accounts, 'array'),
                        'accounts_services' => array($accounts_services, 'array'),
                        'response'          => 1
                    ),
                    'struct'
                );
            }
            else
            {
                // The branch doesn't exist
                $response = array(
                    array(
                        'response'  => 0
                    ),
                    'struct'
                );
            }

        }
        else
        {
            // The client doesn't exist
            $response = array(
                array(
                    'response'  => 0
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the client data and settings
     *
     * Used by: (Local App)
     *      sync/sync_client/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function get_client_updates($request)
    {
        //  0   :   client id
        $parameters = $request->output_parameters();

        // Get the client data and settings
        $this->db->select('name as company_name, logo');
        $this->db->where('id', $parameters[0]);
        $query = $this->db->get('clients');

        // Prepare the client data and settings
        foreach($query->row_array() as $key => $value)
        {
            $updates[] = array(
                array(
                    'name'  => $key,
                    'value' => $value
                ),
                'struct'
            );
        }

        $response = array(
            array(
                'updates'   => array($updates, 'array'),
                'response'  => 1
            ),
            'struct'
        );

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the branch data and settings
     *
     * Used by: (Local App)
     *      sync/sync_branch/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function get_branch_updates($request)
    {
        //  0   :   branch id
        $parameters = $request->output_parameters();

        // Get the branch data and settings
        $this->db->select('name as `branch_name`, street_address, city, state, country_id, contact_number, account_id as id');
        $this->db->where('id', $parameters[0]);
        $query = $this->db->get('branches');

        $branch = $query->row_array();

        // Prepare the branch data and settings except for the account id (id)
        foreach($branch as $key => $value)
        {
            if(strcmp($key, 'id') != 0)
            {
                $updates[] = array(
                    array(
                        'name'  => $key,
                        'value' => $value
                    ),
                    'struct'
                );
            }
        }

        // Get the branch manager account
        $this->db->where('id', $branch['id']);
        $query = $this->db->get('accounts');

        // Prepare the branch manager account
        foreach($query->result_array() as $values)
        {
            $account[] = array(
                $values,
                'struct'
            );
        }

        // Set 'changed' status to 0
        $this->db->where('id', $branch['id']);
        $this->db->update('branches', array('changed' => 0));

        $response = array(
            array(
                'updates'   => array($updates, 'array'),
                'account'   => array($account, 'array'),
                'response'  => 1
            ),
            'struct'
        );

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the data for the specified table
     *
     * Used by: (Local App)
     *      sync/sync_database/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function get_updates($request)
    {
        //  0   :   table name
        //  1   :   id value
        $parameters = $request->output_parameters();

        $id = $this->build_select($parameters[0]);

        $this->db->where_in($id, $parameters[1]);
        $query = $this->db->get($parameters[0]);

        // Check if records exists
        if($query->num_rows() > 0)
        {
            // Prepare the data
            foreach($query->result_array() as $row)
            {
                $updates[] = array(
                    $row,
                    'struct'
                );

                // Set the 'changed' value to 0, doesn't apply to the agents_services table
                if(strcmp($parameters[0], 'agents_services') != 0)
                {
                    $id_val = strcmp($parameters[0], 'agents') ? $row['id'] : $row['agent_id'];
                    $id = $this->build_select($parameters[0]);
                    $this->db->where('id', $id_val);
                    $this->db->update($parameters[0], array('changed' => 0));
                }
            }

            $response = array(
                array(
                    'updates'   => array($updates, 'array'),
                    'response'  => 1
                ),
                'struct'
            );
        }
        else
        {
            $response = array(
                array(
                    'response'  => 0
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Returns the agent's services
     *
     * Used by: (Local App)
     *      sync/initialize_accounts_services/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function initialize_accounts_services($request)
    {
        //  agent ids
        $parameters = $request->output_parameters();

        $this->build_select('agents_services');

        // Get the agent's services
        $this->db->where_in('agent_id', $parameters);
        $query = $this->db->get('agents_services');

        if($query->num_rows() > 0)
        {
            // Prepare the accounts services
            foreach($query->result_array() as $row)
            {
                $accounts_services[] = array(
                    $row,
                    'struct'
                );
            }

            $response = array(
                array(
                    'accounts_services'  => array($accounts_services, 'array'),
                    'response'  => 1
                ),
                'struct'
            );
        }
        else
        {
            $response = array(
                array(
                    'response'  => 0
                ),
                'struct'
            );
        }

        return $this->xmlrpc->send_response($response);
    }

    /**
     * Receive individual logs
     *
     * Used by: (Local App)
     *      sync/send_logs/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function receive_logs($request)
    {
        //  log data
        $parameters = $request->output_parameters();

        $insert = array(
            'agent_id'          => $parameters[1],
            'timestart'         => $parameters[2],
            'timeend'           => $parameters[3],
            'processing_time'   => $parameters[4],
            'issue_time'        => $parameters[5],
            'queue_number'      => $parameters[6],
            'mobile_number'     => $parameters[7],
            'closing_code'      => $parameters[8],
            'client_service_id' => $parameters[9]
        );
        $this->db->insert('logs', $insert);

        return $this->xmlrpc->send_response(1);
    }

    /**
     * Receive daily statistics
     *
     * Used by: (Local App)
     *      sync/send_statistics/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function receive_statistics($request)
    {
        //  0   :   statistics
        //  1   :   service_tally
        //  2   :   closing_code_tally
        //  3   :   dtr
        $parameters = $request->output_parameters();

        foreach($parameters[0] as $row)
        {
            $this->db->insert('statistics', $row);
        }

        foreach($parameters[1] as $row)
        {
            $this->db->insert('services_tally', $row);
        }

        foreach($parameters[2] as $row)
        {
            $this->db->insert('closing_codes_tally', $row);
        }

        foreach($parameters[3] as $row)
        {
            $this->db->insert('dtr', $row);
        }

        return $this->xmlrpc->send_response(1);
    }

    /**
     * Deactivate the branch
     *
     * Used by: (Local App)
     *      sync/deactivate/
     *
     * @author  CSU OJT Students '10 - '11 (Michael Roland B. Martin)
     * @param	object
     *      request :   contains the xml rpc request data
     */
    function deactivate($request)
    {
        //  0   :   branch id
        $parameters = $request->output_parameters();

        $this->db->where('id', $parameters[0]);
        $this->db->update('branches', array('activated' => 0));

        return $this->xmlrpc->send_response(1);
    }

}

/* End of file listen.php */
/* Location: ./system/application/controllers/listen.php */